package com.zxb.base.auth;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxb.base.auth.vo.UserBatchVo;
import com.zxb.base.auth.vo.UserInfoVo;
import com.zxb.core.common.*;
import com.zxb.core.dao.auth.AuthUser;
import com.zxb.core.dao.auth.AuthUserDao;
import com.zxb.core.util.PwdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class UserController {
    private final AuthUserDao userDao;

    @GetMapping("/user/info")
    public R findUserInfo() {
        User user = Req.getCurrUser();
        AuthUser authUser = userDao.getOne(
                new LambdaQueryWrapper<AuthUser>()
                        .eq(AuthUser::getUsername, user.getUsername()));
        if (authUser == null) {
            return R.error("用户不存在");
        }
        return R.success(authUser);
    }

    @GetMapping("/user/page")
    public R page(String searchStr, Integer page, Integer pageSize) {
        IPage<AuthUser> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<AuthUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(searchStr)) {
            queryWrapper.like(AuthUser::getSearchStr, "%" + searchStr + "%");
        }
        IPage<AuthUser> result = userDao.page(pageParam, queryWrapper);
        return R.success(result);
    }

    @PostMapping("/user/add")
    public R add(@RequestBody @Valid AuthUser obj) {
        if (userDao.exists(
                new QueryWrapper<AuthUser>()
                        .lambda()
                        .eq(AuthUser::getUsername, obj.getUsername())
        )) {
            return R.error("用户名已经被使用");
        }
        if (userDao.exists(
                new QueryWrapper<AuthUser>()
                        .lambda()
                        .eq(AuthUser::getPhone, obj.getPhone())
        )) {
            return R.error("手机号已经被使用");
        }
        obj.setPassword(PwdUtil.generateDefaultPwd());
        obj.setNamePy(PinyinUtil.getPinyin(obj.getName()));
        obj.setIsTest(false);
        obj.setSearchStr(obj.getUsername() + obj.getName());
        userDao.save(obj);
        return R.success();
    }

    @PostMapping("/user/update")
    public R update(@RequestBody @Valid AuthUser obj) {
        AuthUser old = userDao.getById(obj.getId());
        A.isInDatabase(old, "用户");
        if (userDao.exists(
                new QueryWrapper<AuthUser>()
                        .lambda()
                        .eq(AuthUser::getUsername, obj.getUsername())
                        .ne(AuthUser::getId, old.getId())
        )) {
            return R.error("用户名已经被使用");
        }

        if (userDao.exists(
                new QueryWrapper<AuthUser>()
                        .lambda()
                        .eq(AuthUser::getPhone, obj.getPhone())
                        .ne(AuthUser::getId, old.getId())
        )) {
            return R.error("手机号已经被使用");
        }

        BeanUtil.copyProperties(obj, old, C.IGNORED_PROPERTIES);
        obj.setNamePy(PinyinUtil.getPinyin(obj.getName()));
        obj.setSearchStr(obj.getUsername() + obj.getName());
        userDao.updateById(old);
        return R.success();
    }

    @PostMapping("/user/del")
    public R del(@RequestBody List<Long> ids) {
        userDao.removeBatchByIds(ids);
        return R.success();
    }

    @PostMapping("/user/batch")
    @Transactional(rollbackFor = Exception.class)
    public R batch(@RequestBody UserBatchVo param) {
        List<Long> idList = param.getIds();
        for (Long id : idList) {
            AuthUser old = userDao.getById(id);
            if (old != null) {
                if (param.getIsPwdCk()) {
                    old.setPassword(param.getPwd());
                }
                if (param.getIsSexCk()) {
                    old.setSex(param.getSex());
                }
                if (param.getIsEduLevelCk()) {
                    old.setEduLevel(param.getEduLevel());
                }
                if (param.getIsOpenCk()) {
                    old.setIsOpen(param.getIsOpen());
                }
                userDao.updateById(old);
            }
        }
        return R.success();
    }
    @PostMapping("/user/save")
    public R save(@RequestBody @Valid UserInfoVo obj) {
        AuthUser old = userDao.getById(obj.getId());
        A.isInDatabase(old, "用户");
        BeanUtil.copyProperties(obj, old, C.IGNORED_PROPERTIES);
        old.setNamePy(PinyinUtil.getPinyin(old.getName()));
        old.setSearchStr(old.getUsername() + old.getName());
        userDao.updateById(old);
        return R.success();
    }
}
